import { useEffect } from "react";
import { Space, Pagination, Divider, Table, Select, message, Dropdown, Popconfirm } from "antd";
import { DownOutlined } from "@ant-design/icons";
import { Button, ButtonGroup, Card as SemiCard } from "@douyinfe/semi-ui";
import { IconPlusCircle, IconRefresh } from "@douyinfe/semi-icons";
import { useModel } from "umi";
import { useReactive } from "ahooks";
import { useRelatedOrganization } from "@share-code/public";

import AddRelateOrganization from "../components/add.relate.organization";

const { Column } = Table;

const AllAffiliateOrganizations = () => {
    const { remoteData, UTCTimeToLocal, windowInnerHeight, graphqlFetch } = useModel("global");
    const { setModalVisible, setModalTitle, setModalComponent, setModalStyle } = useModel("global.modal");
    const { baseInfo } = useModel("person.info");
    const { organizationUuid, organizationInfo } = useModel("organization.info");

    const {
        loadAllRelatedOrganizationsWithPage,
        updateRelatedOrganizationStatus,
        updateRelatedOrganizationRelateType,
    } = useRelatedOrganization(graphqlFetch);

    const state = useReactive({
        loading: false,
        affiliates: [],
        totalCount: 0,
        pageSize: 20,
        page: 1,
        selectedType: "",
        types: [
            { label: "业务关系", value: "业务关系", key: "业务关系" },
            { label: "股东关系", value: "股东关系", key: "股东关系" },
            { label: "同级组织", value: "同级组织", key: "同级组织" },
            { label: "直属上级", value: "直属上级", key: "直属上级" },
            { label: "直属下级", value: "直属下级", key: "直属下级" },
            { label: "主管单位", value: "主管单位", key: "主管单位" },
        ],
    });

    const loadAffiliates = async () => {
        state.loading = true;
        let variables = { first: state.pageSize, offset: (state.page - 1) * state.pageSize };
        if (state.selectedType) variables.oaRela = state.selectedType;
        let res = await loadAllRelatedOrganizationsWithPage(variables);
        state.affiliates = res?.data || [];
        state.totalCount = res?.totalCount || 0;
        state.loading = false;
    };

    useEffect(() => {
        loadAffiliates();
    }, [state.page, state.selectedType]);

    const openAffiliateAddModal = () => {
        setModalTitle("添加关联组织");
        setModalStyle({ top: 100 });
        setModalComponent(<AddRelateOrganization affiliates={state.affiliates} reloadData={loadAffiliates} />);
        setModalVisible(true);
    };

    const reApply = async (record) => {
        let res = await remoteData({
            object: "multi-organization-gateway",
            serviceName: "/api/public_api_service",
            organizationUuid: record.oaUuid,
            params: {
                apiPath: "/organization/relatedApply",
                data: {
                    oaUuid: organizationUuid,
                    oaName: organizationInfo.fullName,
                    oaCaus: "重新申请",
                    oaApid: baseInfo.uuid,
                    oaApna: baseInfo.realName,
                },
            },
        });
        if (res) {
            if (res?.oaStat === "待审核") {
                message.warning((res?.oaCaus ? res.oaCaus + ", " : "") + "申请待审核中");
            }
            if (res?.oaStat === "正常") {
                message.success("申请关联的组织已确认");
                let res = await updateRelatedOrganizationStatus({
                    oaUuid: record.oaUuid,
                    oaStat: "正常",
                    oaAust: true,
                });
                if (res) {
                    message.success("转正常组织关联操作成功");
                    loadAffiliates();
                }
            }
        }
    };

    const updateRelation = async (oaUuid, oaRela) => {
        let res = await updateRelatedOrganizationRelateType({ oaRela, oaUuid });
        if (res) {
            message.success("成功更新组织关系信息");
            loadAffiliates();
        }
    };

    const removeRelation = async (record) => {
        let res = await remoteData({
            object: "multi-organization-gateway",
            serviceName: "/api/public_api_service",
            organizationUuid: record.oaUuid,
            params: {
                apiPath: "/organization/relatedRemove",
                data: {
                    oaUuid: organizationUuid,
                },
            },
        });
        if (res) {
            if (res?.oaStat === "已解除") {
                let res = await updateRelatedOrganizationStatus({
                    oaUuid: record.oaUuid,
                    oaStat: "已解除",
                    oaAust: true,
                });
                if (res) {
                    message.success("解除关联组织关系操作成功");
                    loadAffiliates();
                }
            }
        }
    };

    const cardBodyHeight = windowInnerHeight - 90 - 20 - 48 - 60;

    return (
        <SemiCard
            title={<span style={{ lineHeight: "32px", fontSize: 15 }}>关联组织列表</span>}
            headerStyle={{ padding: "7px 12px" }}
            headerExtraContent={
                <Space>
                    <div style={{ fontWeight: "normal" }}>关系筛选: </div>
                    <Select
                        value={state.selectedType}
                        style={{ width: 160 }}
                        allowClear
                        options={state.types}
                        onChange={(value) => (state.selectedType = value)}
                    />
                    <ButtonGroup>
                        <Button icon={<IconPlusCircle />} onClick={() => openAffiliateAddModal()}>
                            添加关联组织
                        </Button>
                        <Button icon={<IconRefresh />} onClick={() => loadAffiliates()}>
                            刷新
                        </Button>
                    </ButtonGroup>
                </Space>
            }
            shadows="always"
            bordered={false}
            bodyStyle={{ padding: 0, height: cardBodyHeight }}
            footerStyle={{ padding: 0 }}
            footerLine={true}
            footer={
                <div style={{ padding: 14, display: "flex", justifyContent: "space-between" }}>
                    <div style={{ lineHeight: "32px" }}>关联组织数: {state.totalCount}</div>
                    <Pagination
                        total={state.totalCount}
                        showTotal={(total, range) => `当前显示第 ${range[0]}-${range[1]} 条，共 ${total} 条`}
                        pageSize={state.pageSize}
                        current={state.page}
                        showSizeChanger={false}
                        onChange={(page, pageSize) => (state.page = page)}
                    />
                </div>
            }
        >
            <Table
                loading={state.loading}
                bordered
                size="small"
                pagination={false}
                dataSource={state.affiliates}
                rowKey={"oaUuid"}
                scroll={{ y: cardBodyHeight - 40 }}
            >
                <Column
                    title="序号"
                    dataIndex="orderNo"
                    align="center"
                    width={80}
                    render={(_, record, index) => (state.page - 1) * state.pageSize + index + 1}
                />
                <Column title="组织名称" dataIndex="oaName" align="left" />
                <Column title="组织关系" dataIndex="oaRela" align="center" width={160} />
                <Column title="关联原由" dataIndex="oaCaus" align="center" width={200} />
                <Column
                    title="申请时间"
                    align="center"
                    width={160}
                    render={(_, record) => UTCTimeToLocal(record.oaApti)}
                />
                <Column
                    title="是否发起方"
                    align="center"
                    width={120}
                    render={(_, record) => (record.oaIsme ? "是" : "否")}
                />
                <Column
                    title="审核状态"
                    align="center"
                    width={100}
                    render={(_, record) =>
                        record.oaAust ? <span className="green">已核准</span> : <span className="red">待核准</span>
                    }
                />
                <Column title="关系状态" dataIndex="oaStat" align="center" width={100} />
                <Column
                    title="操作"
                    key="operations"
                    align="center"
                    width={200}
                    render={(_, record) => {
                        return (
                            <Space split={<Divider type="vertical" />} size={0}>
                                <Dropdown
                                    menu={{
                                        items: state.types,
                                        onClick: ({ key }) => updateRelation(record.oaUuid, key),
                                    }}
                                    trigger={["click"]}
                                >
                                    <a onClick={(e) => e.preventDefault()}>
                                        <Space>
                                            变更关系
                                            <DownOutlined />
                                        </Space>
                                    </a>
                                </Dropdown>
                                <Popconfirm title="确认要解除关联关系吗?" onConfirm={() => removeRelation(record)}>
                                    <a>解除关系</a>
                                </Popconfirm>
                                {/* {record.oaIsme && <a onClick={() => reApply(record)}>重新申请</a>} */}
                            </Space>
                        );
                    }}
                />
            </Table>
        </SemiCard>
    );
};

export default AllAffiliateOrganizations;
